﻿using DatabaseTransfer.Forms;
using DatabaseTransfer.Logs;
using DatabaseTransfer.Tables;
using DatabaseTransfer.Utils;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseTransfer.Transfer
{
    public class DataTransfer
    {
        private static ILog logger = LogFactory.GetLogger(typeof(DataTransfer));

        private Interfaces.AbstractDatabase srcDatabase;
        private Interfaces.AbstractDatabase destDatabase;
        private List<ColumnLinkage> linkages;
        private Table srcTable;
        private Table destTable;

        public DataTransfer(Table srcTable, Table destTable, List<ColumnLinkage> linkages)
        {
            this.srcTable = srcTable;
            this.destTable = destTable;
            this.linkages = linkages;
            this.srcDatabase = srcTable.Database;
            this.destDatabase = destTable.Database;
        }

        internal string Transfer()
        {
            String err = "";
            List<TableColumn> srcColumns = new List<TableColumn>();

            foreach (ColumnLinkage linkage in linkages)
            {
                srcColumns.Add(linkage.SourceColumn);
            }


            TableResults srcResults = srcDatabase.GetData(srcTable.TableName, srcColumns);
            if (srcResults == null) {
                err = "Source results came back empty";       
                logger.Error(err, null);
                return err;
            }

            List<TableColumn> destColumns = new List<TableColumn>();
            foreach (ColumnLinkage linkage in linkages)
            {
                linkage.DestinationColumn.ColumnConversion = linkage.Conversion;
                destColumns.Add(linkage.DestinationColumn);
            }

            destDatabase.WriteData(destTable.TableName, destColumns, srcResults);

            return err;
        }
    }
}
